package com.firefly.mq.redisMq.timer;

import com.firefly.mq.redisMq.container.DelayBucket;
import com.firefly.mq.redisMq.container.JobPool;
import com.firefly.mq.redisMq.container.ReadyQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description: 开启延时任务的定时计划
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/10/28
 **/
@Component
public class DelayTimer implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private DelayBucket delayBucket;
    @Autowired
    private JobPool jobPool;
    @Autowired
    private ReadyQueue readyQueue;

    @Value("${thread.size}")
    private int length;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ExecutorService executorService = new ThreadPoolExecutor(length,length,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
        for (int i = 0; i < length; i++) {
            executorService.execute(new DelayJobHandler(delayBucket,jobPool,readyQueue,i));
        }
    }
}

